package com.onlyphoto.onlymall.mvp.view.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import com.onlyphoto.onlymall.R
import com.onlyphoto.onlymall.base.BaseFragment
import com.onlyphoto.onlymall.mvp.contract.CShop
import com.onlyphoto.onlymall.mvp.presenter.PShopImpl

import android.os.Bundle
import android.view.Gravity
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.onlyphoto.onlymall.bean.ShopBean
import com.onlyphoto.onlymall.mvp.view.binder.ShopBinder
import com.yanzhenjie.recyclerview.*
import kotlinx.android.synthetic.main.fragment_shop.*
import me.drakeet.multitype.Items
import me.drakeet.multitype.MultiTypeAdapter
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import android.view.ViewGroup
import com.yanzhenjie.recyclerview.SwipeMenuItem
import androidx.core.content.ContextCompat
import com.onlyphoto.onlymall.bean.request.UpdateShopBean
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import androidx.recyclerview.widget.DividerItemDecoration
import com.onlyphoto.onlymall.bean.request.CartGoodsBean
import com.onlyphoto.onlymall.bean.request.ShopCartDeleteBean
import com.onlyphoto.onlymall.bean.response.GoodsDetailsBean
import com.onlyphoto.onlymall.events.GetStyleEvent
import com.onlyphoto.onlymall.mvp.view.activity.LoginActivity
import com.onlyphoto.onlymall.mvp.view.activity.OrderConfirmActivity
import com.onlyphoto.onlymall.utils.*
import com.onlyphoto.onlymall.widget.StylePopupView
import me.bakumon.statuslayoutmanager.library.DefaultOnStatusChildClickListener
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager
import java.lang.StringBuilder


class ShopFragment : BaseFragment<PShopImpl>(), CShop.IVMall, View.OnClickListener, OnRefreshListener {

    var adapter: MultiTypeAdapter? = null
    var layoutManager: LinearLayoutManager? = null
    var items: Items? = null
    var isEdit = false
    var products = arrayListOf<ShopBean>()
    var totalMoney = 0.00
    var amountMoney = 0.00
    var updateBean: UpdateShopBean? = null
    var deletePosition = 0
    var isSwipe = false
    private val deleteBean = ShopCartDeleteBean()
    private var stylePopupView: StylePopupView? = null
    var eventCartId = 0
    var styleStr = ""
    var buyNum = 0

    override fun retry() {
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        EventBus.getDefault().register(this)

    }

    override fun init() {
        initCustomerStatusManager()
        initRv()
        initListener()
        loadData()
    }

    override fun isLogin(): Boolean {
        return ConfigUtil.instance.loginStatus
    }

    override fun showLogin() {
        ll_login.visibility = View.VISIBLE
        sr_shop.visibility = View.GONE
        ll_cost.visibility = View.GONE
        edit.visibility = View.GONE
    }

    private fun loadData(){
        mPresenter?.getShoppingCart()
    }

    override fun onRefresh(refreshlayout: RefreshLayout?) {
        loadData()
    }

    // 创建菜单：
    private val mSwipeMenuCreator = SwipeMenuCreator { leftMenu, rightMenu, position ->
        //编辑
        /*val modifyItem = SwipeMenuItem(activity)
                .setBackgroundColor(ContextCompat.getColor(activity!!,R.color.theme_color))
                .setText("编辑")
                .setTextColor(ContextCompat.getColor(activity!!,R.color.black))
                .setTextSize(15) // 文字大小。
                .setWidth(140)
                .setHeight(ViewGroup.LayoutParams.MATCH_PARENT)
        rightMenu.addMenuItem(modifyItem)*/
        //删除
        val deleteItem = SwipeMenuItem(activity)
        deleteItem.setText("删除")
                .setBackgroundColor(ContextCompat.getColor(activity!!, R.color.red))
                .setTextColor(ContextCompat.getColor(activity!!,R.color.white)) // 文字颜色。
                .setTextSize(15) // 文字大小。
                .setWidth(180).height = ViewGroup.LayoutParams.MATCH_PARENT

        rightMenu.addMenuItem(deleteItem)
    }

    // 菜单点击监听。
    private val mItemMenuClickListener = OnItemMenuClickListener { menuBridge, position ->
        // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
        menuBridge.closeMenu()

        val menuPosition = menuBridge.position // 菜单在RecyclerView的Item中的Position。
        if (menuPosition == 0) {
            deletePosition = position
            isSwipe = true
            deleteBean.cart_id = (items?.get(position) as ShopBean).id.toString()
            mPresenter?.delete()
        }
    }

    private fun initRv(){
        adapter = MultiTypeAdapter()
        layoutManager = LinearLayoutManager(activity)
        layoutManager?.orientation = RecyclerView.VERTICAL
        val binder = ShopBinder()
        binder.setUpdateListener(object :ShopBinder.UpdateNumListener{
            override fun updateNum(bean: UpdateShopBean) {
                mPresenter?.updateShoppingCart(bean)
            }
        })
        adapter?.register(ShopBean::class.java, binder)
        //添加分割线
        val dividerItemDecoration = DividerItemDecoration(activity, DividerItemDecoration.VERTICAL)
        dividerItemDecoration.setDrawable(ContextCompat.getDrawable(activity!!, R.drawable.dividing)!!)
        rv_shop.addItemDecoration(dividerItemDecoration)
        rv_shop.layoutManager = layoutManager


        // 设置监听器。
        rv_shop.setSwipeMenuCreator(mSwipeMenuCreator)
        rv_shop.setOnItemMenuClickListener(mItemMenuClickListener)
        rv_shop.adapter = adapter

        items = Items()

        adapter?.items = items!!

    }

    @SuppressLint("SetTextI18n")
    override fun getShoppingCartSuccess(list: ArrayList<ShopBean>) {
        items?.clear()
        items?.addAll(list)
        products.clear()
        adapter?.notifyDataSetChanged()
        sr_shop.finishRefresh()
        for (bean in list) {
            if (bean.state == 1) {
                products.add(bean)
            }
        }
        updateTotalPrice()
    }

    override fun updateShoppingCartSuccess() {
        for ((index, bean) in (items as ArrayList<*>).withIndex()) {
            if ((bean as ShopBean).id == updateBean?.cart_id) {
                bean.buy_num = updateBean?.buy_num!!
                bean.style = updateBean?.style!!
                bean.color = updateBean?.color!!
                bean.size = updateBean?.size!!
                adapter?.notifyItemChanged(index, "count")
            }
        }
        updateTotalPrice()
    }

    override fun updateShoppingCartFail() {
        for ((index, bean) in (items as ArrayList<*>).withIndex()) {
            if ((bean as ShopBean).id == updateBean?.cart_id) {
                adapter?.notifyItemChanged(index, "count")
            }
        }
    }

    override fun deleteSuccess() {
        if (isSwipe) {
            products.remove(items!![deletePosition])
            items?.remove(items!![deletePosition])
        } else {
            for (product in products) {
                items?.remove(product)
            }
            products.clear()
        }
        adapter?.notifyDataSetChanged()
        updateTotalPrice()
        if (items?.size == 0) {
            showEmpty()
        }
    }

    override fun getDetailsSuccess(bean: GoodsDetailsBean) {
        if (stylePopupView == null){
            stylePopupView = StylePopupView(activity)
        }
        stylePopupView?.setFinishedListener {
            val updateBean = UpdateShopBean(1, eventCartId, it.goods_id, it.buy_num,
                    it.state, it.style, it.size, it.color)
            this.updateBean = updateBean
            mPresenter?.updateShoppingCart(updateBean)
        }
        stylePopupView?.loadData(bean, styleStr, buyNum)
        stylePopupView?.setButton(StylePopupView.SURE)
        val window = activity?.window
        val lp = window?.attributes
        lp?.alpha = 0.38f
        window?.attributes = lp
        stylePopupView?.showAtLocation(cl_shop, Gravity.BOTTOM, 0, 0)
    }

    private fun deleteProducts(){
        val id = StringBuilder()
        for ((index, product) in products.withIndex()) {
            if (index == products.size - 1) {
                id.append(product.id)
            } else {
                id.append(product.id).append(",")
            }
        }
        deleteBean.cart_id = id.toString()
        mPresenter?.delete()
    }

    override fun getDeleteEntity(): ShopCartDeleteBean {
        return deleteBean
    }

    override fun showMsg(msg: String) {
        ToastUtil.showToast(msg)
    }

    private fun initListener(){
        edit.setOnClickListener(this)
        commit.setOnClickListener(this)
        cb_all.setOnClickListener(this)
        login.setOnClickListener(this)
        sr_shop.setOnRefreshListener(this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
             R.id.edit ->
                if (!isEdit) {
                    isEdit = true
                    edit.text = "完成"
                    commit.text = "删除"
                    cl_amount.visibility = View.GONE
                    commit.background = ContextCompat.getDrawable(activity!!, R.drawable.red_border_trans)
                    commit.setTextColor(ContextCompat.getColor(activity!!, R.color.red))
                } else {
                    isEdit = false
                    edit.text = "编辑"
                    commit.text = "结算"
                    cl_amount.visibility = View.VISIBLE
                    commit.background = ContextCompat.getDrawable(activity!!, R.drawable.btn_common)
                    commit.setTextColor(ContextCompat.getColor(activity!!, R.color.white))
                }
            R.id.commit ->
                if (isEdit) {
                    isSwipe = false
                    deleteProducts()
                } else {
                    if (products.size == 0) {
                        return
                    }
                    val list = java.util.ArrayList<CartGoodsBean>()
                    var bean: CartGoodsBean
                    for (product in products) {
                        bean = CartGoodsBean()
                        bean.id = product.id
                        bean.img = product.front_img
                        bean.name = product.title
                        bean.price = product.price_now
                        bean.goods_id = product.goods_id
                        bean.buy_num = product.buy_num
                        bean.style = product.style
                        bean.color = product.color
                        bean.size = product.size
                        if (product.gift_arr != null) {
                            bean.gift_title = product.gift_arr.title
                        }
                        list.add(bean)
                    }
                    startActivity(Intent(activity, OrderConfirmActivity::class.java)
                            .putExtra("goodsList", list))
                }
            R.id.cb_all -> {
                if (cb_all.isChecked) {
                    for (shopBean in items!!) {
                        var bean = (shopBean as ShopBean)
                        if (bean.state == 2) {
                            bean.state = 1
                        }
                        products.add(bean)
                    }
                    adapter?.notifyDataSetChanged()
                } else {
                    for (shopBean in items!!) {
                        val bean = (shopBean as ShopBean)
                        if (bean.state == 1) {
                            bean.state = 2
                        }
                    }
                    products.clear()
                    adapter?.notifyDataSetChanged()
                }
                updateTotalPrice()
            }
            R.id.login -> startActivity(Intent(activity, LoginActivity::class.java))
        }
    }

    override fun getLayoutRes(): Int {
        return R.layout.fragment_shop
    }

    fun initCustomerStatusManager() {
        builder = StatusLayoutManager.Builder(sr_shop)
                .setDefaultLoadingText("数据加载中...")
                .setOnStatusChildClickListener(object : DefaultOnStatusChildClickListener() {
                    override fun onCustomerChildClick(view: View) {
                        super.onCustomerChildClick(view)
                        when (view.id) {
                            R.id.ll_content -> {
                                when {
                                    view.tag == NetWorkStatus.FAIL -> retry()
                                    view.tag == NetWorkStatus.ERROR -> retry()
                                    view.tag == NetWorkStatus.EMPTY -> {
                                    }
                                }
                            }
                            else -> retry()
                        }
                    }
                })
                .setDefaultLayoutsBackgroundColor(Color.WHITE)
        statusLayoutManager = builder!!.build()
    }

    override fun showEmpty() {
        sr_shop.finishRefresh()
        commonStatusView!!.setContent(R.mipmap.no_details, "购物车空空～", "")
        commonStatusView!!.setType(NetWorkStatus.EMPTY)
        showCustomLayout(commonStatusView!!, R.id.ll_content)
        ll_cost.visibility = View.GONE
        edit.visibility = View.GONE
    }

    override fun updateView() {
        showSuccess()
        ll_login.visibility = View.GONE
        sr_shop.visibility = View.VISIBLE
        ll_cost.visibility = View.VISIBLE
        edit.visibility = View.VISIBLE
    }

    override fun createPresenter() {
        mPresenter = PShopImpl(mContext, this)
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(bean: ShopBean) {
        if (bean.state == 1 && !products.contains(bean)) {
            products.add(bean)
        } else {
            if (products.contains(bean)) {
                products.remove(bean)
            }
        }
        updateTotalPrice()
    }

    @SuppressLint("SetTextI18n")
    fun updateTotalPrice(){
        var account = 0.00
        var checkAll = true
        for (shopBean in items as ArrayList<*>) {
            if ((shopBean as ShopBean).state == 1) {
                account += shopBean.price_now * shopBean.buy_num
            } else {
                checkAll = false
            }
        }
        cb_all.isChecked = checkAll

        total.text = "合计：¥ " + NumUtil.getTwoDecimal(account)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(bean: UpdateShopBean) {
        updateBean = bean
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: GetStyleEvent) {
        mPresenter?.getDetails(event.goodsId)
        styleStr = event.styleStr
        buyNum = event.num
        eventCartId = event.cartId
    }

    override fun onDetach() {
        super.onDetach()
        EventBus.getDefault().unregister(this)
    }

    override fun showLoading() {}

    override fun hideLoading() {}

    companion object {

        fun newInstance(): ShopFragment {
            val fragment = ShopFragment()
            val args = Bundle()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onResume() {
        super.onResume()
        loadData()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            loadData()
        }
    }
}
